package cn.com.pc.content.controller;

import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpStatus;
import org.elasticsearch.action.admin.cluster.health.ClusterHealthRequest;
import org.elasticsearch.action.admin.cluster.health.ClusterHealthResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.rest.RestResponse;
import org.elasticsearch.rest.RestStatus;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;


@Slf4j
@RequestMapping("/health")
@RestController
public class HealthController {

    @Resource
    private RestHighLevelClient restHighLevelClient;

    /**
     * 应用健康接口
     * @return
     */
    @SneakyThrows
    @GetMapping
    public String health(HttpServletResponse httpServletResponse){
        ClusterHealthResponse response = restHighLevelClient.cluster().health(new ClusterHealthRequest(), RequestOptions.DEFAULT);
        if(response.status().getStatus() != RestStatus.OK.getStatus()) {
            log.warn("es健康检查异常:{}", response);
            httpServletResponse.setStatus(response.status().getStatus());
        }
        return response.toString();
    }
}